package com.axonactive.yolo.monitor;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;

import com.axonactive.yolo.exception.ExchangeRateNotFoundException;
import com.axonactive.yolo.service.interfaces.ExchangeRateService;
import com.axonactive.yolo.util.IOUtil;

public class UpdateExchangeRate {

	@Autowired
	private ExchangeRateService exchangeRateService;
	
	private final static Logger LOGGER = Logger.getLogger(UpdateExchangeRate.class);
	private final static String URL_CURRENCY_API = "https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json";

	public boolean run() throws ExchangeRateNotFoundException, ClientProtocolException, IOException, ParseException, InterruptedException {
		LOGGER.info("UpdateExchangeRate IN");

		String response = IOUtil.call(URL_CURRENCY_API);
		JSONParser jsonParser = new JSONParser();
		JSONObject jsonObject = (JSONObject) jsonParser.parse(response);
		
		jsonObject = (JSONObject)jsonObject.get("list");
		
		JSONArray currencies = new JSONArray(String.valueOf(jsonObject.get("resources")));
				
		for (int i = 0; i < currencies.length(); i++) {
			org.json.JSONObject currency = (org.json.JSONObject)currencies.getJSONObject(i).get("resource");
			currency = (org.json.JSONObject)currency.get("fields");
			
			String code = currency.getString("symbol").split("=")[0]; // eg: "symbol" : "KRW=X",
			double rate = currency.getDouble("price");
			
			exchangeRateService.update(code, rate);
			LOGGER.info(code + ": update successfully");
		}
		
		LOGGER.info("UpdateExchangeRate OUT");
		return true;
	}
}